<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>复杂表头表格示例</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        th, td {
             
            padding: 0px;
            
            text-align: center;
        }
        th {
     
            font-weight: bold;
            white-space: nowrap;
            overflow: visible;
            width: auto;
        }
        
        .layer-2 {
            white-space: nowrap;
            overflow: visible;
            width: auto;
        }
        .data-row:nth-child(even) {
            background-color: #f9f9f9;
        }
        .data-row:hover {
            background-color: #f1f1f1;
        }
        
        /* 自定义样式 - 基于表头JSON中的className */
        .project-name {
            
            font-weight: bold;
        }
        .monthly-actual-group {
            background-color: #fff7e6;
        }
        .monthly-budget-group {
            background-color: #f6ffed;
        }
        .yearly-actual-group {
            background-color: #e6fffb;
        }
        .yearly-budget-group {
            background-color: #f0f9ff;
        }
        .monthly-completion, .yearly-completion {
            background-color: #fff2f0;
        }
        .occupancy-rate {
            background-color: rgba(255, 215, 0, 0.1);
        }
        .avg-price {
            background-color: rgba(34, 139, 34, 0.1);
        }
        .total-income {
            background-color: rgba(0, 128, 255, 0.1);
        }
        .td_unit {
            height: 20px;    line-height: 20px;border-top: 1px solid #ccc;
        }
       .td_cell {
           padding: 5px;
            
        }  
        .header-group {
           background-color: #d3cee2;
        } 
        table.header-table {
            border-collapse: separate;
            border-spacing: 4px;
            background: #fff;
            border: none;
        }
        table.header-table th {
             
        }
        .header-table .td_unit {
            border-top: 4px solid #fff;
            
        }
        .rowspan3 .td_unit {
            
            margin-top: 28px;
        }
        .layer-2 {
            background-color: #e9e7f2;
        }
        .header-table th.project-name {
            width: 150px;
            min-width: 150px;
            max-width: 150px;
        }

        .data-row td {
            border-bottom: 1px dashed #ccc;
            height: 20px;
        }
        .header-table td {
            z-index: 100; 
        }

        /* 固定表头和数据区的第一列 */
        .header-table th:first-child {
            position: sticky;
            left: 0;
            z-index: 10; 
        }
        .table-scroll-x {
            overflow-x: auto;
            width: 100%;
        }
        .header-table {
            min-width: 1200px; /* 或根据实际列数设置 */
        }
        .header-table th,
        .header-table td {
          /* 其它样式 */
        }
 
        .header-table td:first-child ,.project-name {
            position: sticky;
            left: 0;
            z-index: 999;
            background-color: white;
        }
    </style>
</head>
<body>
     
    <div class="table-scroll-x">
        <table id="dataTable"></table>
    </div>

    <script>
        // 表头和数据配置
        const tableConfig = {
            headers: [
                {
                    label: "项目名称",
                    rowspan: 2,
                    colspan: 1,
                  
                    className: "project-name header-group",
                    dataIndex:"project-name"
                },
                {
                    label: "月累计实际",
                    rowspan: 1,
                    colspan: 3,
                    className: "header-group layer-1",
                    children: [
                         
                        {
                            label: "月累计出租率",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "monthlyActual.occupancyRate",
                            className: "occupancy-rate layer-2",
                            unit: "%",
                            is_extendfield: true,
                            
                        },     

                        {
                            label: "月累计总收入",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "monthlyActual.totalIncome",
                            className: "total-income layer-2",
                            unit: "万元",
                            is_extendfield: false,
                        },
                        {
                            label: "月累计总收入3",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "monthlyActual.totalIncome",
                            className: "total-income layer-2",
                            unit: "万元",
                            is_extendfield: false,
                        }
                    ]
                },
                {
                    label: "全月预算",
                    rowspan: 1,
                    colspan: 3,
                    className: "header-group layer-1",
                    children: [
                        {
                            label: "全月预算出租率",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "monthlyBudget.occupancyRate",
                            className: "occupancy-rate layer-2",
                            unit: "%",
                            is_extendfield: false,
                        },
                        {
                            label: "全月预算平均房价",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "monthlyBudget.avgPrice",
                            className: "avg-price layer-2",
                            unit: "元",
                            is_extendfield: false,
                        },
                        {
                            label: "全月预算总收入",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "monthlyBudget.totalIncome",
                            className: "total-income layer-2",
                            unit: "万元",
                            is_extendfield: false,
                        }
                    ]
                },
                {
                    label: "月累计完成率",
                    rowspan: 2,
                    colspan: 1,
                    dataIndex: "monthlyCompletion",
                    className: "header-group layer-1",
                
                },
                {
                    label: "年累计实际",
                    rowspan: 1,
                    colspan: 3,
                    className: "header-group layer-1",
                    children: [
                        {
                            label: "年累计实际出租率",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "yearlyActual.occupancyRate",
                            className: "occupancy-rate layer-2",
                            unit: "%",
                            is_extendfield: true,
                        },
                        {
                            label: "年累计实际平均房价",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "yearlyActual.avgPrice",
                            className: "avg-price layer-2",
                            unit: "元",
                            is_extendfield: false,
                        },
                        {
                            label: "年累计实际总收入",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "yearlyActual.totalIncome",
                            className: "total-income layer-2",
                            unit: "万元",
                            is_extendfield: false,
                        },
                        {
                            label: "年累计实际总收入2",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "yearlyActual.totalIncome",
                            className: "total-income layer-2",
                            unit: "万元",
                            is_extendfield: false,
                        }
                    ]
                },
                {
                    label: "全年预算",
                    rowspan: 1,
                    colspan: 3,
                    className: "header-group layer-1",
                    children: [
                        {
                            label: "全年预算出租率",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "yearlyBudget.occupancyRate",
                            className: "occupancy-rate layer-2",
                            unit: "%",
                            is_extendfield: false,
                        },
                        {
                            label: "平均房价",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "yearlyBudget.avgPrice",
                            className: "avg-price layer-2",
                            unit: "元",
                            is_extendfield: false,
                        },
                        {
                            label: "总收入",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "yearlyBudget.totalIncome",
                            className: "total-income layer-2",
                            unit: "万元",
                            is_extendfield: false,
                        },
                        {
                            label: "全年bc总收入2",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "yearlyBudget.totalIncome",
                            className: "total-income layer-2",
                            unit: "万元",
                            is_extendfield: false,
                        },
                        {
                            label: "全年预算总收入3",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "yearlyBudget.totalIncome",
                            className: "total-income layer-2",
                            unit: "万元",
                            is_extendfield: false,
                        },
                        {
                            label: "全年预算总收入4",
                            rowspan: 1,
                            colspan: 1,
                            dataIndex: "yearlyBudget.totalIncome",
                            className: "total-income layer-2",
                            unit: "万元",
                            is_extendfield: false,
                        }
                    ]
                },
                {
                    label: "年累计完成率",
                    rowspan: 2,
                    colspan: 1,
                    dataIndex: "yearlyCompletion",
                    className: "header-group layer-1" 
                }
            ]
        };

        // 生成表头矩阵（严格树转二维表头，支持混合结构）
        function getHeaderDepth(headers) {
            let max = 1;
            headers.forEach(h => {
                if (h.children && h.children.length > 0) {
                    max = Math.max(max, 1 + getHeaderDepth(h.children));
                }
            });
            return max;
        }

        // 修复后的fillHeaderMatrix函数
        function fillHeaderMatrix(headers, depth, row = 0, col = 0, matrix = [], leafNodes = []) {
            matrix[row] = matrix[row] || [];
            let curCol = col;
            headers.forEach(header => {
                let cell = {
                    label: header.label || '',
                    className: header.className || '',
                    unit: header.unit || '',
                    rowspan: 1,
                    colspan: 1,
                    isLeaf: !header.children || header.children.length === 0,
                    _header: header,
                    originalRowspan: header.rowspan || 1  // 保存原始rowspan值
                };
                
                if (header.children && header.children.length > 0) {
                    // 有子节点的情况
                    let childCol = curCol;
                    fillHeaderMatrix(header.children, depth, row + 1, childCol, matrix, leafNodes);
                    cell.colspan = countLeaf(header.children);
                    cell.rowspan = 1;
                } else {
                    // 叶子节点：使用原始rowspan或计算rowspan
                    if (header.rowspan && header.rowspan > 1) {
                        cell.rowspan = header.rowspan;
                    } else {
                        cell.rowspan = depth - row;
                    }
                    cell.colspan = 1;
                    leafNodes.push(cell);
                }
                
                matrix[row][curCol] = cell;
                curCol += cell.colspan;
            });
            return matrix;
        }

        // 修复后的renderHeaderTable函数
        function renderHeaderTable(headers) {
            const depth = getHeaderDepth(headers);
            let leafNodes = [];
            const matrix = fillHeaderMatrix(headers, depth, 0, 0, [], leafNodes);
            
            // 确保矩阵有足够的行数
            for (let i = 0; i < depth; i++) {
                matrix[i] = matrix[i] || [];
            }
            
            let html = '<table class="header-table" border="0">';
            
            // 渲染表头行
            for (let i = 0; i < depth; i++) {
                html += '<tr>';
                for (let j = 0; j < matrix[i].length; j++) {
                    const cell = matrix[i][j];
                    if (!cell || cell._rendered) continue;
                    
                    let attrs = '';
                    if (cell.rowspan > 1) attrs += ` rowspan="${cell.rowspan}"`;
                    if (cell.colspan > 1) attrs += ` colspan="${cell.colspan}"`;
                    if (cell.className) attrs += ` class="rowspan${cell.rowspan} ${cell.className}"`;
                    
                    html += `<th${attrs}> <div class='text td_cell'>${cell.label}</div>
                        ${cell.unit ? `<div class="td_unit td_cell">${cell.unit}</div>` : ''}
                         </th>`;
                    
                    // 标记被合并的格子
                    for (let r = 0; r < cell.rowspan; r++) {
                        for (let c = 0; c < cell.colspan; c++) {
                            if (r === 0 && c === 0) continue;
                            if (!matrix[i + r]) matrix[i + r] = [];
                            matrix[i + r][j + c] = { _rendered: true, _parentCell: cell };
                        }
                    }
                }
                html += '</tr>';
            }
            

            html += '</table>';
            return html;
        }

        function countLeaf(headers) {
            let count = 0;
            headers.forEach(h => {
                if (h.children && h.children.length > 0) {
                    count += countLeaf(h.children);
                } else {
                    count++;
                }
            });
            return count;
        }

        // 生成mock数据
        function getAllDataIndex(headers, arr = []) {
            headers.forEach(h => {
                if (h.dataIndex) arr.push(h.dataIndex);
                if (h.children && h.children.length > 0) getAllDataIndex(h.children, arr);
            });
            return arr;
        }
        function mockData(headers, rowCount = 10) {
            const fields = getAllDataIndex(headers);
            const data = [];
            for (let i = 0; i < rowCount; i++) {
                const row = {};
                fields.forEach(f => {
                    // 简单mock：数字+下标
                    row[f] = typeof i === 'number' ? `${f}_${i+1}` : '';
                });
                data.push(row);
            }
            return data;
        }

        // 渲染数据行
        function renderDataRows(headers, data) {
            // 获取所有叶子节点（顺序与表体一致）
            let leafNodes = [];
            function collectLeafs(hs) {
                hs.forEach(h => {
                    if (h.children && h.children.length > 0) collectLeafs(h.children);
                    else leafNodes.push(h);
                });
            }
            collectLeafs(headers);
            let html = '';
            data.forEach(row => {
                html += '<tr class="data-row">';
                leafNodes.forEach(h => {
                    html += `<td>${row[h.dataIndex] || ''}</td>`;
                });
                html += '</tr>';
            });
            return html;
        }

        // 用法
        const tableHtml = renderHeaderTable(tableConfig.headers);
        const mock = mockData(tableConfig.headers, 10);
        const dataRowsHtml = renderDataRows(tableConfig.headers, mock);
        // 插入表头和数据
        const tableWrap = document.createElement('div');
        tableWrap.innerHTML = tableHtml.replace('</table>', dataRowsHtml + '</table>');
        document.body.appendChild(tableWrap);
    </script>
</body>
</html>
